package tree.binarysearchtree;

import tree.TreeNode;

/**
 * @Classname : DeleteNodeInABST
 * @Description :
 * <a href="https://leetcode.cn/problems/delete-node-in-a-bst/">450. 删除二叉搜索树中的节点</a>
 * @Author : chentianyu
 * @Date 2023/1/29 15:49
 */


public class DeleteNodeInABST {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;

        if (root.val > key) root.left = deleteNode(root.left, key);
        else if (root.val < key) root.right = deleteNode(root.right, key);
        else {
            if (root.left != null && root.right != null) {
                TreeNode rightMin = findMin(root.right);
                root.val = rightMin.val;
                root.right = deleteNode(root.right, rightMin.val);
            } else {
                if (root.left != null) root = root.left;
                else root = root.right;
            }
        }
        return root;
    }

    private TreeNode findMin(TreeNode root) {
        if (root == null || root.left == null) return root;
        return findMin(root.left);
    }
}
